<template>
  <div class="login-page">
    <!-- Header -->
    <AppHeader />

    <!-- Main Content -->
    <div class="auth-container">
      <!-- Left Brand Section -->
      <div class="brand-section">
        <div class="brand-content">
          <div class="brand-logo">
            <NearLogo :size="48" variant="primary" />
          </div>
          <div class="brand-text">
            <h1 class="brand-title">{{ $t('auth.brandTitle') }}</h1>
            <h2 class="brand-subtitle">{{ $t('auth.brandSubtitle') }}</h2>
            <div class="brand-line"></div>
            <p class="brand-copyright">{{ $t('auth.brandCopyright') }}</p>
          </div>
        </div>

        <!-- 动态金融数据展示 -->
        <div class="financial-animation">
          <!-- 主要趋势图表 -->
          <div class="main-chart">
            <TrendChart :width="280" :height="100" :is-positive="true" />
          </div>

          <!-- 浮动价格卡片 -->
          <FloatingPriceCard
            v-for="(crypto, index) in cryptoData"
            :key="crypto.name"
            :crypto-data="crypto"
            :animation-delay="index * 0.5"
            :float-direction="index % 2 === 0 ? 'up' : 'down'"
            :style="getCardPosition(index)"
          />

          <!-- 统计数据展示 -->
          <div class="stats-display">
            <div class="stat-item">
              <div class="stat-label">총시가</div>
              <div class="stat-value">
                <AnimatedNumber :value="totalMarketCap" :decimals="0" suffix="B" />
              </div>
            </div>
            <div class="stat-item">
              <div class="stat-label">24h거래량</div>
              <div class="stat-value">
                <AnimatedNumber :value="dailyVolume" :decimals="1" suffix="B" />
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Right Form Section -->
      <div class="form-section">
        <div class="form-container">
          <h2 class="form-title">{{ $t('auth.login.title') }}</h2>

          <el-form :model="loginForm" class="login-form" @submit.prevent="handleLogin">
            <el-form-item :label="$t('auth.login.username')">
              <el-input
                v-model="loginForm.username"
                :placeholder="$t('auth.login.username')"
                size="large"
                class="form-input"
              />
            </el-form-item>

            <el-form-item :label="$t('auth.login.password')">
              <el-input
                v-model="loginForm.password"
                type="password"
                :placeholder="$t('auth.login.password')"
                size="large"
                class="form-input"
                show-password
              />
            </el-form-item>

            <div class="form-actions">
              <el-button
                type="primary"
                size="large"
                class="login-btn"
                @click="handleLogin"
              >
                {{ $t('auth.login.loginBtn') }}
              </el-button>
            </div>

            <div class="form-links">
              <el-button
                link
                class="find-credentials-btn"
                @click="showFindMessage"
              >
                {{ $t('auth.login.findCredentials') }}
              </el-button>
            </div>

            <div class="register-link">
              <span>{{ $t('auth.login.noAccount') }}</span>
              <router-link to="/register" class="link">
                {{ $t('auth.login.registerLink') }}
              </router-link>
            </div>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import AppHeader from '@/components/Header/AppHeader.vue'
import NearLogo from '@/components/Common/NearLogo.vue'
import FloatingPriceCard from '@/components/Common/FloatingPriceCard.vue'
import AnimatedNumber from '@/components/Common/AnimatedNumber.vue'
import TrendChart from '@/components/Common/TrendChart.vue'

const { t } = useI18n()
const router = useRouter()
const userStore = useUserStore()

const loginForm = ref({
  username: '',
  password: ''
})

// 动态金融数据
const totalMarketCap = ref(0)
const dailyVolume = ref(0)

const cryptoData = ref([
  {
    name: 'NEAR',
    icon: 'cryptocurrency:near',
    price: 4.52,
    change: 5.23,
    decimals: 2
  },
  {
    name: 'BTC',
    icon: 'cryptocurrency:btc',
    price: 43250.00,
    change: -2.15,
    decimals: 0
  },
  {
    name: 'ETH',
    icon: 'cryptocurrency:eth',
    price: 2680.45,
    change: 3.84,
    decimals: 0
  },
  {
    name: 'BNB',
    icon: 'cryptocurrency:bnb',
    price: 315.20,
    change: 1.92,
    decimals: 2
  }
])

// 获取卡片位置
const getCardPosition = (index: number) => {
  const positions = [
    { top: '5%', right: '20%' },
    { top: '25%', left: '5%' },
    { top: '45%', left: '25%' },
    { top: '15%', right: '5%' }
  ]
  return positions[index] || { top: '40%', left: '50%' }
}

const handleLogin = async () => {
  // 表单验证
  if (!loginForm.value.username) {
    ElMessage.error('사용자명을 입력해주세요')
    return
  }

  if (!loginForm.value.password) {
    ElMessage.error('비밀번호를 입력해주세요')
    return
  }

  try {
    // 使用用户状态管理器进行登录
    const success = await userStore.login(loginForm.value.username, loginForm.value.password)

    if (success) {
      // 显示成功消息
      const currentUserName = userStore.userInfo.value?.name ?? ''
      ElMessage.success(`환영합니다, ${currentUserName}님!`)

      // 跳转到钱包仪表板
      router.push('/app/dashboard')
    } else {
      ElMessage.error('로그인에 실패했습니다. 사용자명과 비밀번호를 확인해주세요')
    }
  } catch (error: any) {
    console.error('로그인 실패:', error)
    ElMessage.error('로그인에 실패했습니다. 나중에 다시 시도해주세요')
  }
}

const showFindMessage = () => {
  ElMessage.info(t('auth.login.findMessage'))
}

// 初始化动画数据
onMounted(() => {
  // 延迟启动数据动画，营造逐步加载的效果
  setTimeout(() => {
    totalMarketCap.value = 2340
    dailyVolume.value = 58.7
  }, 1000)

  // 定期更新价格数据以模拟实时效果
  const priceUpdateInterval = setInterval(() => {
    cryptoData.value.forEach(crypto => {
      const changePercent = (Math.random() - 0.5) * 0.1 // ±5%的随机变化
      crypto.price = Math.max(0.01, crypto.price * (1 + changePercent))
      crypto.change = (Math.random() - 0.5) * 10 // ±5%的涨跌幅
    })
  }, 5000)

  // 清理定时器
  const cleanup = () => clearInterval(priceUpdateInterval)

  // 在组件卸载时清理
  if (typeof window !== 'undefined') {
    window.addEventListener('beforeunload', cleanup)
  }
})
</script>

<style scoped lang="scss">
.login-page {
  min-height: 100vh;
  background: white;
  display: flex;
  flex-direction: column;
}


.auth-container {
  flex: 1;
  display: flex;
  min-height: calc(100vh - 64px);
}

.brand-section {
  flex: 1;
  background: white;
  display: flex;
  align-items: flex-end;
  justify-content: flex-start;
  padding: 40px;
  position: relative;
  overflow: hidden;

  .brand-content {
    text-align: left;
    max-width: 500px;
    color: #1a202c;

    .brand-logo {
      position: absolute;
      top: -60px;
      left: -20px;
    }

    .brand-text {
      .brand-title {
        font-size: 36px;
        font-weight: 600;
        color: #1a202c;
        margin-bottom: 12px;
        line-height: 1.2;
      }

      .brand-subtitle {
        font-size: 20px;
        font-weight: 400;
        color: #64748b;
        margin-bottom: 24px;
        line-height: 1.4;
      }

      .brand-line {
        width: 60px;
        height: 4px;
        background: #7c3aed;
        margin-bottom: 24px;
      }

      .brand-copyright {
        font-size: 15px;
        color: #94a3b8;
        line-height: 1.4;
      }
    }
  }

  // 动态金融数据展示样式
  .financial-animation {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    pointer-events: none;
    z-index: 1;

    .main-chart {
      position: absolute;
      top: 20%;
      right: 10%;
      opacity: 0.7;
      animation: fadeInChart 2s ease-out 0.5s both;
    }

    .stats-display {
      position: absolute;
      bottom: 30%;
      right: 15%;
      display: flex;
      gap: 20px;
      animation: slideInStats 1.5s ease-out 1.5s both;

      .stat-item {
        background: rgba(255, 255, 255, 0.9);
        backdrop-filter: blur(10px);
        border: 1px solid rgba(124, 58, 237, 0.1);
        border-radius: 12px;
        padding: 16px;
        text-align: center;
        box-shadow: 0 4px 20px rgba(124, 58, 237, 0.1);
        transition: transform 0.3s ease;

        &:hover {
          transform: translateY(-2px);
        }

        .stat-label {
          font-size: 12px;
          color: #64748b;
          margin-bottom: 8px;
          font-weight: 500;
        }

        .stat-value {
          font-size: 18px;
          font-weight: 700;
          color: #1a202c;
        }
      }
    }
  }

  .brand-content {
    z-index: 10;
    position: relative;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(5px);
    border-radius: 16px;
    padding: 20px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  }
}

.form-section {
  flex: 1;
  background: white;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;

  .form-container {
    width: 100%;
    max-width: 400px;
    background: white;
    padding: 40px;
    border-radius: 12px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    border: 1px solid #e2e8f0;

    .form-title {
      font-size: 32px;
      font-weight: 600;
      color: #1a202c;
      text-align: center;
      margin-bottom: 32px;
      white-space: nowrap;
    }

    .login-form {
      :deep(.el-form-item) {
        margin-bottom: 20px;
        display: flex;
        flex-direction: row;
        align-items: center;

        .el-form-item__label {
          color: #374151;
          font-weight: 500;
          font-size: 14px;
          line-height: 1.5;
          margin-bottom: 0;
          text-align: left;
          width: 100px !important;
          min-width: 100px;
          padding: 0 12px 0 0 !important;
          position: relative;
          float: none !important;
          flex-shrink: 0;
        }

        .el-form-item__content {
          margin-left: 0 !important;
          flex: 1;
          width: auto;
        }
      }

      .form-input {
        margin-bottom: 16px;

        :deep(.el-input__wrapper) {
          border-radius: 8px;
          padding: 12px 16px;
          border: 1px solid #e2e8f0;

          &:hover {
            border-color: #7c3aed;
          }

          &.is-focus {
            border-color: #7c3aed;
            box-shadow: 0 0 0 3px rgba(124, 58, 237, 0.1);
          }
        }
      }

      .form-actions {
        margin: 24px 0;

        .login-btn {
          width: 100%;
          height: 48px;
          background: #7c3aed;
          border: none;
          border-radius: 8px;
          font-weight: 600;
          font-size: 16px;

          &:hover {
            background: #6d28d9;
          }
        }
      }

      .form-links {
        text-align: center;
        margin-bottom: 24px;

        .find-credentials-btn {
          color: #7c3aed;
          font-size: 14px;

          &:hover {
            color: #6d28d9;
          }
        }
      }

      .register-link {
        text-align: center;
        font-size: 14px;
        color: #64748b;

        .link {
          color: #7c3aed;
          text-decoration: none;
          margin-left: 4px;

          &:hover {
            color: #6d28d9;
            text-decoration: underline;
          }
        }
      }
    }
  }
}

// 动画关键帧
@keyframes fadeInChart {
  from {
    opacity: 0;
    transform: translateX(30px);
  }
  to {
    opacity: 0.7;
    transform: translateX(0);
  }
}

@keyframes slideInStats {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 响应式设计
@media (max-width: 1024px) {
  .auth-container {
    flex-direction: column;
  }

  .brand-section {
    flex: none;
    padding: 20px;
    align-items: center;

    .brand-content {
      text-align: center;

      .brand-logo {
        position: static;
        margin-bottom: 20px;
      }

      .brand-text {
        .brand-title {
          font-size: 20px;
        }

        .brand-subtitle {
          font-size: 14px;
        }
      }
    }

    .financial-animation {
      position: static;
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
      gap: 12px;
      margin-top: 20px;
      pointer-events: auto;

      .main-chart {
        position: static;
        order: 1;
        width: 100%;
        display: flex;
        justify-content: center;
        margin-bottom: 16px;
      }

      .stats-display {
        position: static;
        order: 3;
        width: 100%;
        justify-content: center;

        .stat-item {
          padding: 12px;

          .stat-label {
            font-size: 11px;
          }

          .stat-value {
            font-size: 16px;
          }
        }
      }
    }
  }

  .form-section {
    flex: none;
    padding: 20px;

    .form-container {
      padding: 24px;
    }
  }
}

@media (max-width: 768px) {
  .auth-header {
    .header-container {
      padding: 0 16px;
    }
  }

  .brand-section {
    padding: 16px;
  }

  .form-section {
    padding: 16px;

    .form-container {
      padding: 20px;
    }
  }
}
</style>
